#include<iostream>
#include<string.h>

#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

#include"UdpClient.hpp"
#include"Common.hpp"

//以命令行参数利用服务器ip和port启动【./udp_Client sever_ip sever_port】
int main(int argc,char*argv[])
{
    //1.格式：
    if(argc != 3)
    {
        std::cerr << "Usage: " << "sever_ip sever_port" << std::endl;
        Die(1);
    }
    std::string severip = argv[1];
    uint16_t severport = std::stoi(argv[2]);

    //2.创建套接字
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        
        Die(2);
    }

    //3.填充sever信息
    struct sockaddr_in sever;
    memset(&sever,0,sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_port =::htons(severport);
    sever.sin_addr.s_addr = ::inet_addr(severip.c_str());

    /*4.启动客户端并发送打印信息
    客户端会在首次发送时OS自动bind客户端自己的ip and port!!!(随机绑定端口号)
    服务器必须显示用bind以保证稳定性*/
    while(true)
    {
        std::cout << "Please enter# ";
        std::string message;
        std::getline(std::cin,message);

        ::sendto(sockfd,message.c_str(),message.size(),0,CONV(&sever),sizeof(sever));

        //发送成功收消息
        char buffer[1024];    
        struct sockaddr_in tmp;        
        socklen_t len = sizeof(tmp);   
        ssize_t n = ::recvfrom(sockfd,buffer,sizeof(buffer)-1,0,CONV(&tmp),&len);
        if(n > 0)
        {
            
            buffer[n] = 0;
            std::cout << buffer <<std::endl;
        }
    }
    return 0;
}